/**
 * 后端应用设置
 */
import { getLogger, Service } from '@gnlab/utils'
import { MemSubject } from '@gnlab/utils/rx'
import type { Services } from '@/services'
import { API } from '@/services/common/api'

const logger = getLogger('services/features/web-config')

export interface WebConfig {
  // openapi 的回调 URL：QunTool 后端会请求此网址来向客户发送通知
  // 相关文档：https://ll64kbqo4j.feishu.cn/docx/QYhrdnq4pouQ1mxt2pWcJxZ6nUd
  notifyUrl: string

  // QunTool 后端调用企业微信平台的接口需要的信息，可配置多个
  qywxAPIConfigs: QywxAPIConfig[]
}

export interface QywxAPIConfig {
  corpId: string
  secret: string
  corpIdOrigin: string
}

export const defaults: WebConfig = {
  notifyUrl: '',
  qywxAPIConfigs: [],
}

export class WebConfigSrv extends Service<Services> {
  private get auth() {
    return this.services.auth
  }

  registered() {
    void Promise.resolve(this.auth.accountId).then(() => {
      if (this.auth.account$.value?.isAdmin === true) {
        void this.load()
      }
    })
  }

  // 当前设置值
  data = new MemSubject<WebConfig>(defaults)

  /**
   * 从服务器端拉取设置
   */
  async load() {
    interface RawWebConfig {
      NotifyUrl: string | null
      WxApiConfig: {
        CorpId: string
        CorpSecret: string
        CorpIdOrigin: string
      }[]
    }
    const res = await API('/WebConfig/GetWebConfigs', {
      formatter(raw: RawWebConfig): WebConfig {
        return {
          notifyUrl: raw.NotifyUrl ?? '',
          qywxAPIConfigs: raw.WxApiConfig.map(item => ({
            corpId: item.CorpId,
            secret: item.CorpSecret,
            corpIdOrigin: item.CorpIdOrigin,
          })),
        }
      },
    })
    if (res.success) {
      this.data.next(res.data)
    } else {
      logger.warn('设置获取失败', res.error)
    }
  }

  /**
   * 修改设置
   */
  async update(config: WebConfig) {
    const res = await API('/WebConfig/SaveWebConfigs', {
      data: {
        notifyUrl: config.notifyUrl,
        wxApiConfig: config.qywxAPIConfigs.map(item => ({
          corpid: item.corpId,
          corpSecret: item.secret,
          corpIdOrigin: item.corpIdOrigin,
        })),
      },
    })
    if (res.success) {
      logger.info('修改成功', config)
      this.data.next(config)
    } else logger.warn('修改失败', { config, error: res.error })
    return res
  }
}
